package com.itboye.ihomebank.activity.me;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.camera.CameraActivity;
import com.itboye.ihomebank.custom.camera.PermissionTest;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.uploadmultipleimage.MultipartRequest;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.CameraPopupWindow;
import com.itboye.ihomebank.util.SPUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * 实名认证
 */
public class ActivityRealName extends BaseOtherActivity implements Observer {
    View v_statusbar;
    private ImageView close_icon;// 返回图片
    private TextView add_shap_title_tv;// 标题
    private EditText real_name;// 真实姓名
    private EditText real_code, real_yinhangka, real_yuliuphone, real_yzm;// 身份证号
    private TextView real_tijiao;// 提交

    private UserPresenter userPresenter;

    private String uid;// id

    private String realname;// 真实姓名
    private String ibnumber;// 身份证号
    private String code;// 验证码

    ImageView real_img01, real_img02;

    CameraPopupWindow mCameraPopupWindow;

    /**
     * 身份证正面的选择
     */
    private String localSelectPath01;
    /**
     * 身份证背面的选择
     */
    private String localSelectPath02;

    private String fileName01;
    private String fileName02;
    private String type;
    private String yinhangka;
    private String phone;
    TextView sendyzm;

    private int bit_width = 0;
    private int bit_height = 0;
    private Uri mOutPutFileUri;



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                break;
            case R.id.real_tijiao:// 提交认证
                realname = real_name.getText().toString();
                ibnumber = real_code.getText().toString();
                yinhangka = real_yinhangka.getText().toString();
                code = real_yzm.getText().toString();
                phone = real_yuliuphone.getText().toString();
                if (TextUtils.isEmpty(real_name.getText())) {
                    ByAlert.alert("请输入真实姓名");
                    return;
                }
                if (TextUtils.isEmpty(real_code.getText())) {
                    ByAlert.alert("请输入身份证号");
                    return;
                }
//                if (TextUtils.isEmpty(yinhangka)) {
//                    ByAlert.alert("请输入银行卡号");
//                    return;
//                }
                if (phone.equals("")) {
                    ByAlert.alert("请输入本人手机号");
                    return;
                }
                showProgressDialog("请求提交中,请稍后", false);
                String[] img = {localSelectPath01, localSelectPath02};
                String url = NetPublicConstant.URL + "/file/upload?client_id=by565fa4facdb191";
                Map<String, String> params = new HashMap<String, String>();
                params.put("uid", uid);
                params.put("type", "ID");
                File f1 = null;
                File f2 = null;
                if (localSelectPath01 == null || localSelectPath02 == null) {
                    ByAlert.alert("请先选择有效图片");
                    return;
                }
                f1 = new File(localSelectPath01);
                f2 = new File(localSelectPath02);
                List<File> f = new ArrayList<File>();
                f.add(f1);
                f.add(f2);
                MultipartRequest request = new MultipartRequest(url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                //  ByAlert.alert("上传成功");
                                try {
                                    closeProgressDialog();
                                } catch (Exception e) {
                                }
                                real_tijiao.setEnabled(false);
                                userPresenter.getRealName(uid, realname, ibnumber, "", phone, code);

                            }
                        }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        try {
                            closeProgressDialog();
                            real_tijiao.setEnabled(true);
                        } catch (Exception e) {
                        }
                        ByAlert.alert("上传错误" + error.getMessage());
                    }
                }, "image[]", f, params, 500, bit_width, bit_height); // 注意这个key必须是f_file[],后面的[]不能少
                MyApplcation.addRequest(request);
                break;

            case R.id.real_img01:// 添加身份证正面照片
                type = "zheng";
                pic();
                break;

            case R.id.real_img02:// 添加身份证背面照片
                type = "fan";
                pic();
                break;
            case R.id.sendyzm:// 发送验证码
                phone = real_yuliuphone.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    ByAlert.alert("请输入银行卡预留手机号");
                    return;
                }
                userPresenter.send(phone, "10");
                break;
            default:
                break;
        }
    }

    /**
     * 打开图库
     */
    private void pic() {
        if (!PermissionTest.isCameraPermission()){
            return;
        }
        Intent intent=new Intent(ActivityRealName.this,CameraActivity.class);
        startActivityForResult (intent,111);
    }

    //6.0添加拍照的权限
    private static String[] PERMISSIONS_CAMERA_AND_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};

    public static boolean isCameraPermission(Activity context, int requestCode) {
        if (Build.VERSION.SDK_INT >= 23) {
            int storagePermission = ActivityCompat.checkSelfPermission(context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int cameraPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
            if (storagePermission != PackageManager.PERMISSION_GRANTED || cameraPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(context, PERMISSIONS_CAMERA_AND_STORAGE,
                        requestCode);
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra("select_result");
            String paths = "";
            for (String path : pathList) {
                Log.i("ImagePathList", path);
                paths = pathList.get(0);
            }

            Bitmap bit = BitmapFactory.decodeFile(paths);
            bit_width = bit.getWidth();
            bit_height = bit.getHeight();
            if (type != null) {
                if (type.equals("zheng")) {
                    localSelectPath01 = paths;
                    real_img01.setImageBitmap(bit);
                } else {
                    localSelectPath02 = paths;
                    real_img02.setImageBitmap(bit);
                }
            }
        }
    }

    @Override
    protected int layout_id() {
        // TODO Auto-generated method stub
        return R.layout.activity_real_name;
    }

    @Override
    protected void onInitController() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        userPresenter = new UserPresenter(this);

        add_shap_title_tv.setText("实名认证");
        uid = (String) SPUtils.get(this, null, SPContants.USER_ID, "");
    }

    @Override
    protected void onReadIntent(Bundle bundle) {
        // TODO Auto-generated method stub

    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.realName_success) {
                real_tijiao.setEnabled(true);
                String bean = (String) entity.getData();
                if (bean != null) {
                    ByAlert.alert("申请已经提交,等待审核中...");
                    SPUtils.put(this,"",SPContants.RealName,"");
                    finish();
                }
            } else if (entity.getEventType() == UserPresenter.realName_fail) {
                ByAlert.alert(entity.getMsg());
                real_tijiao.setEnabled(true);

            } else if (entity.getEventType() == UserPresenter.send_success) {
                ByAlert.alert(entity.getData());
            } else if (entity.getEventType() == UserPresenter.send_fail) {
                ByAlert.alert(entity.getData());
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}
